﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using RotovapPlatform.Application.Services.Storages;
using RotovapPlatform.Domain.Business.Machine.Enums;
using RotovapPlatform.Domain.Business.Storage.Entities;
using RotovapPlatform.Domain.Business.Storage.Entities.Base;
using RotovapPlatform.Domain.Business.Storage.Entities.Bottles;
using RotovapPlatform.Domain.Business.Storage.Enums;
using RotovapPlatform.UI.Services;

namespace RotovapPlatform.UI.ViewModels.MaterialManagement
{
	public partial class ShelfViewModel : ObservableObject, IDisposable
	{
		private readonly IStorageAppService _storageService;
		private ShelfSlotViewModel _selectedSlot;
		private bool _isLoading;
		private string _statusMessage;
		private bool _disposed;

		// 货架槽位集合
		public ObservableCollection<ShelfSlotViewModel> TopShelfItems { get; } = new();
		public ObservableCollection<ShelfSlotViewModel> SecondShelfItems { get; } = new();
		public ObservableCollection<ShelfSlotViewModel> ThirdShelfItems { get; } = new();
		public ObservableCollection<ShelfSlotViewModel> BottomShelfItems { get; } = new();
		public ObservableCollection<ShelfSlotViewModel> SecondShelfSpecialItems { get; } = new();
		public ObservableCollection<ShelfSlotViewModel> ThirdShelfSpecialItems { get; } = new();

		// 命令
		public ICommand LoadDataCommand { get; }
		public ICommand AddBottleCommand { get; }
		public ICommand RemoveBottleCommand { get; }
		public ICommand RefreshCommand { get; }

		// 属性
		public ShelfSlotViewModel SelectedSlot
		{
			get => _selectedSlot;
			set
			{
				if (_selectedSlot != value)
				{
					System.Diagnostics.Debug.WriteLine($"ShelfViewModel: SelectedSlot 从 {_selectedSlot?.DisplayPosition ?? "null"} 变更为 {value?.DisplayPosition ?? "null"}");

					if (value != null && value.IsOccupied && value.Bottle != null)
					{
						System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 新选中槽位 {value.DisplayPosition} 的瓶子信息 - 类型: {value.Bottle.Type}, 功能: {value.Bottle.Function}");
					}
				}

				SetProperty(ref _selectedSlot, value);
				OnPropertyChanged(nameof(IsRotovapBottleSelected));
				OnPropertyChanged(nameof(IsCentrifugeBottleSelected));
				OnPropertyChanged(nameof(IsSampleBottleSelected));
				OnPropertyChanged(nameof(IsRotovapEmptySelected));
				OnPropertyChanged(nameof(IsRotovapNotEmptySelected));
				OnPropertyChanged(nameof(IsCentrifugeToRotovapSelected));
				OnPropertyChanged(nameof(IsCentrifugeCondensateCollectionSelected));
				OnPropertyChanged(nameof(IsCentrifugeResidueCollectionSelected));
				OnPropertyChanged(nameof(IsCentrifugeWashLiquidSelected));
				OnPropertyChanged(nameof(IsSampleCondensateSelected));
				OnPropertyChanged(nameof(IsSampleResidueSelected));
				OnPropertyChanged(nameof(SelectedRotovapBottle));
				OnPropertyChanged(nameof(SelectedCentrifugeBottle));
				OnPropertyChanged(nameof(SelectedSampleBottle));
				OnPropertyChanged(nameof(HasExperimentInfo));
			}
		}

		public bool IsLoading
		{
			get => _isLoading;
			set => SetProperty(ref _isLoading, value);
		}

		public string StatusMessage
		{
			get => _statusMessage;
			set => SetProperty(ref _statusMessage, value);
		}

		// 添加OccupiedSlots属性，用于显示所有已占用的槽位
		private ObservableCollection<ShelfSlotViewModel> _occupiedSlots = new();
		public ObservableCollection<ShelfSlotViewModel> OccupiedSlots
		{
			get => _occupiedSlots;
			private set => SetProperty(ref _occupiedSlots, value);
		}

		// 添加特定类型瓶子的属性
		public bool IsRotovapBottleSelected => SelectedSlot?.Bottle is RotovapBottle;
		public bool IsCentrifugeBottleSelected => SelectedSlot?.Bottle is CentrifugeBottle;
		public bool IsSampleBottleSelected => SelectedSlot?.Bottle is SampleBottle;

		// 添加基于功能码的条件判断属性
		public bool IsRotovapEmptySelected => IsRotovapBottleSelected && SelectedRotovapBottle?.Function == FunctionType.Rotovap_Empty;
		public bool IsRotovapNotEmptySelected => IsRotovapBottleSelected && SelectedRotovapBottle?.Function == FunctionType.Rotovap_NotEmpty;

		public bool IsCentrifugeToRotovapSelected => IsCentrifugeBottleSelected && SelectedCentrifugeBottle?.Function == FunctionType.Centrifuge_To_Rotovap;
		public bool IsCentrifugeCondensateCollectionSelected => IsCentrifugeBottleSelected && SelectedCentrifugeBottle?.Function == FunctionType.Centrifuge_Condensate_Collection;
		public bool IsCentrifugeResidueCollectionSelected => IsCentrifugeBottleSelected && SelectedCentrifugeBottle?.Function == FunctionType.Centrifuge_Residue_Collection;
		public bool IsCentrifugeWashLiquidSelected => IsCentrifugeBottleSelected && SelectedCentrifugeBottle?.Function == FunctionType.Centrifuge_Wash_Liquid;

		public bool IsSampleCondensateSelected => IsSampleBottleSelected && SelectedSampleBottle?.Function == FunctionType.Sample_Condensate;
		public bool IsSampleResidueSelected => IsSampleBottleSelected && SelectedSampleBottle?.Function == FunctionType.Sample_Residue;

		// 判断是否有实验信息
		public bool HasExperimentInfo => SelectedSlot?.Bottle != null && SelectedSlot.Bottle.Function != FunctionType.Centrifuge_Wash_Liquid &&
										SelectedSlot.Bottle.ExperimentId.HasValue &&
										(SelectedSlot.Bottle.ExperimentStartTime != default ||
										 SelectedSlot.Bottle.ExperimentEndTime != default ||
										 !string.IsNullOrEmpty(SelectedSlot.Bottle.ExperimentDescription));

		public RotovapBottle? SelectedRotovapBottle => SelectedSlot?.Bottle as RotovapBottle;
		public CentrifugeBottle? SelectedCentrifugeBottle => SelectedSlot?.Bottle as CentrifugeBottle;
		public SampleBottle? SelectedSampleBottle => SelectedSlot?.Bottle as SampleBottle;

		// 添加Slots属性，用于获取所有货架槽位
		public IEnumerable<ShelfSlotViewModel> Slots =>
			TopShelfItems
			.Concat(SecondShelfItems)
			.Concat(ThirdShelfItems)
			.Concat(BottomShelfItems)
			.Concat(SecondShelfSpecialItems)
			.Concat(ThirdShelfSpecialItems);

		// 添加静态标志位，防止递归调用
		private static bool _isRefreshing = false;

		// 构造函数
		public ShelfViewModel(IStorageAppService storageService)
		{
			_storageService = storageService;
			_statusMessage = "准备就绪";

			// 初始化命令
			LoadDataCommand = new AsyncRelayCommand(LoadShelfData);
			RefreshCommand = new AsyncRelayCommand(LoadShelfData);

			// 订阅货架数据更新事件
			EventBus.ShelfDataUpdated += OnShelfDataUpdated;

			// 初始化货架槽位
			InitializeShelf();

			// 加载数据
			_ = LoadShelfData();
		}

		// 初始化货架UI结构
		private void InitializeShelf()
		{
			// 初始化第一层（7个位置）
			for (int i = 0; i < 7; i++)
				TopShelfItems.Add(new ShelfSlotViewModel(i, 1));

			// 初始化第二层（4个标准位置）
			for (int i = 0; i < 4; i++)
				SecondShelfItems.Add(new ShelfSlotViewModel(i, 2));

			// 初始化第二层特殊位置（2个较矮位置）
			for (int i = 0; i < 2; i++)
				SecondShelfSpecialItems.Add(new ShelfSlotViewModel(4 + i, 2));

			// 初始化第三层（4个标准位置）
			for (int i = 0; i < 4; i++)
				ThirdShelfItems.Add(new ShelfSlotViewModel(i, 3));

			// 初始化第三层特殊位置（2个较高位置）
			for (int i = 0; i < 2; i++)
				ThirdShelfSpecialItems.Add(new ShelfSlotViewModel(4 + i, 3));

			// 初始化第四层（5个位置）
			for (int i = 0; i < 5; i++)
				BottomShelfItems.Add(new ShelfSlotViewModel(i, 4));
		}

		// 从数据库加载数据
		private async Task LoadShelfData()
		{
			try
			{
				IsLoading = true;
				StatusMessage = "正在加载数据...";

				// 不再清空现有数据，改用增量更新方式
				// ClearAllBottles();

				// 获取所有货架位置
				var locations = await _storageService.GetAllShelfLocationsAsync();

				// 创建一个字典来跟踪已处理的位置
				var processedPositions = new Dictionary<int, bool>();

				// 清空已占用槽位列表，准备重新填充
				_occupiedSlots.Clear();

				// 标记是否有数据变更
				bool hasChanges = false;

				// 更新UI
				foreach (var location in locations.Where(l => l.IsOccupied && l.CurrentItem != null))
				{
					// 获取位置编号
					int position = location.Position;

					// 记录已处理的位置
					processedPositions[position] = true;

					// 获取显示名称
					string displayName = _storageService.GetShelfDisplayName(position);

					// 解析行列信息
					int row = position / 100;
					int column = position % 100;

					// 根据位置编号找到对应的槽位
					ShelfSlotViewModel slot = FindSlotByPosition(row, column);

					if (slot != null && location.CurrentItem is Bottle bottle)
					{
						// 检查是否需要更新
						bool needUpdate = slot.Bottle == null ||
										 slot.Bottle.Function != bottle.Function ||
										 slot.Bottle.Type != bottle.Type;

						if (needUpdate)
						{
							// 设置瓶子和位置ID
							slot.SetBottle(bottle);
							slot.LocationId = location.Id;

							// 处理DisplayPosition，确保格式为"1-1"
							if (displayName.StartsWith("货架"))
							{
								// 去掉"货架"前缀
								slot.DisplayPosition = displayName.Substring(2);
							}
							else
							{
								slot.DisplayPosition = displayName;
							}

							hasChanges = true;
							System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 更新位置 {slot.DisplayPosition} 的瓶子");
						}
						else
						{
							// 即使不需要更新瓶子，也确保DisplayPosition格式正确
							if (displayName.StartsWith("货架"))
							{
								// 去掉"货架"前缀
								slot.DisplayPosition = displayName.Substring(2);
								System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 修正位置 {slot.DisplayPosition} 的显示名称");
							}
						}

						// 添加到已占用槽位列表
						if (!_occupiedSlots.Contains(slot))
						{
							_occupiedSlots.Add(slot);
						}

						// 记录特殊位置的更新
						if ((row == 2 && (column == 5 || column == 6)) ||
							(row == 3 && (column == 5 || column == 6)))
						{
							System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 更新特殊位置 {displayName}，占用状态: {slot.IsOccupied}");
						}
					}
				}

				// 清除不再占用的位置
				foreach (var slot in Slots.Where(s => s.IsOccupied).ToList())
				{
					// 计算完整的位置编号，与数据库中的位置编号格式一致
					// 注意：Position从0开始，而数据库中从1开始，所以需要+1
					int fullPosition = slot.Layer * 100 + slot.Position + 1;

					System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 检查位置 {slot.DisplayPosition} 是否仍被占用 (完整位置编号: {fullPosition})");

					if (!processedPositions.ContainsKey(fullPosition))
					{
						System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 清除位置 {slot.DisplayPosition} 的瓶子，因为它不再被占用 (完整位置编号: {fullPosition})");
						slot.ClearBottle();
						hasChanges = true;
					}
				}

				// 更新各层货架的集合
				UpdateShelfCollections();

				// 只有在有数据变更时才触发UI刷新
				if (hasChanges)
				{
					// 手动触发集合属性变更通知
					RefreshUICollections();
				}

				StatusMessage = $"数据加载完成，共 {OccupiedSlots.Count} 个已占用槽位";

				// 记录日志
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 数据已加载，共 {OccupiedSlots.Count} 个已占用槽位");
			}
			catch (Exception ex)
			{
				StatusMessage = $"加载数据失败: {ex.Message}";
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 加载数据失败: {ex.Message}");
			}
			finally
			{
				IsLoading = false;
			}
		}

		// 清空所有瓶子
		private void ClearAllBottles()
		{
			// 清空所有层的瓶子
			foreach (var slot in TopShelfItems)
				slot.ClearBottle();

			foreach (var slot in SecondShelfItems)
				slot.ClearBottle();

			foreach (var slot in ThirdShelfItems)
				slot.ClearBottle();

			foreach (var slot in BottomShelfItems)
				slot.ClearBottle();

			foreach (var slot in SecondShelfSpecialItems)
				slot.ClearBottle();

			foreach (var slot in ThirdShelfSpecialItems)
				slot.ClearBottle();

			// 手动触发集合属性变更通知
			OnPropertyChanged(nameof(TopShelfItems));
			OnPropertyChanged(nameof(SecondShelfItems));
			OnPropertyChanged(nameof(ThirdShelfItems));
			OnPropertyChanged(nameof(BottomShelfItems));
			OnPropertyChanged(nameof(SecondShelfSpecialItems));
			OnPropertyChanged(nameof(ThirdShelfSpecialItems));
			OnPropertyChanged(nameof(Slots));
		}

		// 根据行列找到对应的槽位
		private ShelfSlotViewModel FindSlotByPosition(int row, int column)
		{
			System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 查找位置 {row}-{column}");

			// 注意：数据库中的column是从1开始的，而我们的Position是从0开始的，所以需要-1
			int adjustedColumn = column - 1;

			ShelfSlotViewModel result = null;

			switch (row)
			{
				case 1:
					// 第一层
					result = adjustedColumn >= 0 && adjustedColumn < TopShelfItems.Count ? TopShelfItems[adjustedColumn] : null;
					break;
				case 2:
					// 第二层
					if (adjustedColumn >= 0 && adjustedColumn < 4)
						result = SecondShelfItems[adjustedColumn];
					else if (adjustedColumn >= 4 && adjustedColumn < 6)
						result = SecondShelfSpecialItems[adjustedColumn - 4];
					break;
				case 3:
					// 第三层
					if (adjustedColumn >= 0 && adjustedColumn < 4)
						result = ThirdShelfItems[adjustedColumn];
					else if (adjustedColumn >= 4 && adjustedColumn < 6)
						result = ThirdShelfSpecialItems[adjustedColumn - 4];
					break;
				case 4:
					// 第四层
					result = adjustedColumn >= 0 && adjustedColumn < BottomShelfItems.Count ? BottomShelfItems[adjustedColumn] : null;
					break;
			}

			if (result != null)
			{
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 找到位置 {row}-{column}，对应槽位 Layer={result.Layer}, Position={result.Position}, 调整后的列索引={adjustedColumn}");
			}
			else
			{
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 未找到位置 {row}-{column} 对应的槽位，调整后的列索引={adjustedColumn}");
			}

			return result;
		}

		/// <summary>
		/// 更新已占用槽位列表
		/// </summary>
		private void UpdateOccupiedSlots()
		{
			// 清空已占用槽位列表
			_occupiedSlots.Clear();

			// 添加所有已占用的槽位
			foreach (var slot in Slots.Where(s => s.IsOccupied))
			{
				_occupiedSlots.Add(slot);
			}

			// 更新各层货架的集合
			UpdateShelfCollections();

			// 触发属性变更通知
			OnPropertyChanged(nameof(OccupiedSlots));
		}

		/// <summary>
		/// 更新各层货架的集合
		/// </summary>
		private void UpdateShelfCollections()
		{
			System.Diagnostics.Debug.WriteLine("ShelfViewModel: 开始更新各层货架的集合");

			// 更新第一层货架
			UpdateLayerCollection(TopShelfItems, "第一层");

			// 更新第二层货架
			UpdateLayerCollection(SecondShelfItems, "第二层");

			// 更新第二层特殊位置
			UpdateLayerCollection(SecondShelfSpecialItems, "第二层特殊");

			// 更新第三层货架
			UpdateLayerCollection(ThirdShelfItems, "第三层");

			// 更新第三层特殊位置
			UpdateLayerCollection(ThirdShelfSpecialItems, "第三层特殊");

			// 更新第四层货架
			UpdateLayerCollection(BottomShelfItems, "第四层");

			System.Diagnostics.Debug.WriteLine("ShelfViewModel: 各层货架的集合更新完成");
		}

		// 辅助方法，用于更新特定层的集合
		private void UpdateLayerCollection(ObservableCollection<ShelfSlotViewModel> collection, string layerName)
		{
			int updatedCount = 0;
			int clearedCount = 0;

			foreach (var slot in collection)
			{
				// 使用完整位置编号进行比较
				// 注意：Position从0开始，而数据库中从1开始，所以需要+1
				int fullPosition = slot.Layer * 100 + slot.Position + 1;
				var occupiedSlot = _occupiedSlots.FirstOrDefault(s => (s.Layer * 100 + s.Position + 1) == fullPosition);

				if (occupiedSlot != null && !slot.IsOccupied)
				{
					// 先设置DisplayPosition，再设置瓶子
					string displayPosition = occupiedSlot.DisplayPosition;
					if (displayPosition.StartsWith("货架"))
					{
						// 去掉"货架"前缀
						slot.DisplayPosition = displayPosition.Substring(2);
					}
					else
					{
						slot.DisplayPosition = displayPosition;
					}

					slot.SetBottle(occupiedSlot.Bottle);
					slot.LocationId = occupiedSlot.LocationId;
					updatedCount++;
				}
				else if (occupiedSlot == null && slot.IsOccupied)
				{
					slot.ClearBottle();
					clearedCount++;
				}
			}

			if (updatedCount > 0 || clearedCount > 0)
			{
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: {layerName}更新了 {updatedCount} 个槽位，清除了 {clearedCount} 个槽位");
			}
		}

		// 处理全局货架数据更新事件
		private void OnShelfDataUpdated(object sender, EventArgs e)
		{
			// 使用 Dispatcher 确保在 UI 线程上执行
			System.Windows.Application.Current.Dispatcher.Invoke(async () =>
			{
				// 避免重复刷新
				if (IsLoading)
					return;

				System.Diagnostics.Debug.WriteLine("ShelfViewModel: 收到货架数据更新事件，开始刷新数据...");

				// 重新加载货架数据
				await LoadShelfData();

				// 不再需要手动触发集合属性变更通知，因为LoadShelfData已经会触发
				// RefreshUICollections();

				// 记录日志
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 货架数据已更新，共 {OccupiedSlots.Count} 个已占用槽位");
			});
		}

		// 实现IDisposable接口
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (_disposed) return;

			if (disposing)
			{
				// 取消订阅事件
				EventBus.ShelfDataUpdated -= OnShelfDataUpdated;
			}

			_disposed = true;
		}

		~ShelfViewModel()
		{
			Dispose(false);
		}

		// 公共方法，用于刷新货架数据
		public async Task RefreshDataAsync()
		{
			try
			{
				IsLoading = true;
				StatusMessage = "正在刷新数据...";
				System.Diagnostics.Debug.WriteLine("ShelfViewModel: 开始刷新货架数据");

				// 获取所有货架位置
				var locations = await _storageService.GetAllShelfLocationsAsync();

				// 记录占用位置的数量
				var occupiedLocations = locations.Where(l => l.IsOccupied && l.CurrentItem != null).ToList();
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 从数据库获取到 {locations.Count} 个货架位置，其中有 {occupiedLocations.Count} 个位置被占用");

				// 记录每个集合的初始状态（简化日志）
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 刷新前 - 各层货架占用情况：" +
					$"第一层 {TopShelfItems.Count(i => i.IsOccupied)}/{TopShelfItems.Count}, " +
					$"第二层 {SecondShelfItems.Count(i => i.IsOccupied)}/{SecondShelfItems.Count}, " +
					$"第三层 {ThirdShelfItems.Count(i => i.IsOccupied)}/{ThirdShelfItems.Count}, " +
					$"第四层 {BottomShelfItems.Count(i => i.IsOccupied)}/{BottomShelfItems.Count}, " +
					$"第二层特殊 {SecondShelfSpecialItems.Count(i => i.IsOccupied)}/{SecondShelfSpecialItems.Count}, " +
					$"第三层特殊 {ThirdShelfSpecialItems.Count(i => i.IsOccupied)}/{ThirdShelfSpecialItems.Count}");

				// 标记是否有数据变更，避免不必要的UI刷新
				bool hasChanges = false;

				// 创建一个字典来跟踪已处理的位置，键为完整位置编号
				var processedPositions = new Dictionary<int, bool>();

				// 清空已占用槽位列表，准备重新填充
				_occupiedSlots.Clear();

				// 更新UI（减少每个位置的日志输出）
				foreach (var location in locations.Where(l => l.IsOccupied && l.CurrentItem != null))
				{
					// 获取位置编号
					int position = location.Position;

					// 记录已处理的位置
					processedPositions[position] = true;

					// 获取显示名称
					string displayName = _storageService.GetShelfDisplayName(position);

					// 解析行列信息
					int row = position / 100;
					int column = position % 100;

					// 根据位置编号找到对应的槽位
					ShelfSlotViewModel slot = FindSlotByPosition(row, column);

					if (slot != null && location.CurrentItem is Bottle bottle)
					{
						// 检查是否需要更新
						bool needUpdate = slot.Bottle == null ||
										 slot.Bottle.Function != bottle.Function ||
										 slot.Bottle.Type != bottle.Type;

						if (needUpdate)
						{
							// 设置瓶子和位置ID
							slot.SetBottle(bottle);
							slot.LocationId = location.Id;

							// 处理DisplayPosition，确保格式为"1-1"
							if (displayName.StartsWith("货架"))
							{
								// 去掉"货架"前缀
								slot.DisplayPosition = displayName.Substring(2);
							}
							else
							{
								slot.DisplayPosition = displayName;
							}

							hasChanges = true;
						}
						else
						{
							// 即使不需要更新瓶子，也确保DisplayPosition格式正确
							if (displayName.StartsWith("货架"))
							{
								// 去掉"货架"前缀
								slot.DisplayPosition = displayName.Substring(2);
							}
						}

						// 添加到已占用槽位列表
						if (!_occupiedSlots.Contains(slot))
						{
							_occupiedSlots.Add(slot);
						}
					}
					else if (slot == null)
					{
						System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 警告 - 找不到位置 {displayName} 对应的槽位");
					}
				}

				// 清除不再占用的位置（简化日志）
				int clearedCount = 0;
				foreach (var slot in Slots.Where(s => s.IsOccupied).ToList())
				{
					// 计算完整的位置编号，与数据库中的位置编号格式一致
					// 注意：Position从0开始，而数据库中从1开始，所以需要+1
					int fullPosition = slot.Layer * 100 + slot.Position + 1;

					if (!processedPositions.ContainsKey(fullPosition))
					{
						slot.ClearBottle();
						clearedCount++;
						hasChanges = true;
					}
				}

				if (clearedCount > 0)
				{
					System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 清除了 {clearedCount} 个不再被占用的位置");
				}

				// 更新各层货架的集合
				UpdateShelfCollections();

				// 记录每个集合的更新后状态（简化日志）
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 刷新后 - 各层货架占用情况：" +
					$"第一层 {TopShelfItems.Count(i => i.IsOccupied)}/{TopShelfItems.Count}, " +
					$"第二层 {SecondShelfItems.Count(i => i.IsOccupied)}/{SecondShelfItems.Count}, " +
					$"第三层 {ThirdShelfItems.Count(i => i.IsOccupied)}/{ThirdShelfItems.Count}, " +
					$"第四层 {BottomShelfItems.Count(i => i.IsOccupied)}/{BottomShelfItems.Count}, " +
					$"第二层特殊 {SecondShelfSpecialItems.Count(i => i.IsOccupied)}/{SecondShelfSpecialItems.Count}, " +
					$"第三层特殊 {ThirdShelfSpecialItems.Count(i => i.IsOccupied)}/{ThirdShelfSpecialItems.Count}");

				// 无论是否有变更，都强制刷新UI
				// 手动触发集合属性变更通知
				RefreshUICollections();

				StatusMessage = $"数据刷新完成，共 {OccupiedSlots.Count} 个已占用槽位";
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 数据已刷新，共 {OccupiedSlots.Count} 个已占用槽位");
			}
			catch (Exception ex)
			{
				StatusMessage = $"刷新数据失败: {ex.Message}";
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 刷新数据失败: {ex.Message}");
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 异常堆栈: {ex.StackTrace}");
			}
			finally
			{
				IsLoading = false;
			}
		}

		/// <summary>
		/// 手动触发集合属性变更通知，确保UI更新
		/// </summary>
		public void RefreshUICollections()
		{
			// 使用静态标志位防止递归调用
			if (_isRefreshing)
				return;

			try
			{
				_isRefreshing = true;

				// 使用批量更新模式，一次性触发所有属性变更通知
				System.Diagnostics.Debug.WriteLine("ShelfViewModel: 开始批量更新UI集合");

				// 使用Dispatcher.Invoke而不是BeginInvoke，确保UI更新完成后再继续
				System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
				{
					// 在UI线程上一次性触发所有属性变更通知
					OnPropertyChanged(nameof(TopShelfItems));
					OnPropertyChanged(nameof(SecondShelfItems));
					OnPropertyChanged(nameof(ThirdShelfItems));
					OnPropertyChanged(nameof(BottomShelfItems));
					OnPropertyChanged(nameof(SecondShelfSpecialItems));
					OnPropertyChanged(nameof(ThirdShelfSpecialItems));
					OnPropertyChanged(nameof(OccupiedSlots));
					OnPropertyChanged(nameof(Slots));
				}));

				// 记录日志
				System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 已触发UI集合刷新，共 {OccupiedSlots.Count} 个已占用槽位");

				// 只在调试模式下记录特殊位置状态
#if DEBUG
				if (SecondShelfSpecialItems.Count >= 2 && ThirdShelfSpecialItems.Count >= 2)
				{
					System.Diagnostics.Debug.WriteLine($"ShelfViewModel: 特殊位置状态 - 2-5: {SecondShelfSpecialItems[0].IsOccupied}, 2-6: {SecondShelfSpecialItems[1].IsOccupied}, 3-5: {ThirdShelfSpecialItems[0].IsOccupied}, 3-6: {ThirdShelfSpecialItems[1].IsOccupied}");
				}
#endif

				System.Diagnostics.Debug.WriteLine("ShelfViewModel: 批量更新UI集合完成");
			}
			finally
			{
				_isRefreshing = false;
			}
		}

		// 更新OnPropertyChanged方法，添加对特定类型瓶子属性的通知
		protected override void OnPropertyChanged(PropertyChangedEventArgs e)
		{
			base.OnPropertyChanged(e);

			if (e.PropertyName == nameof(SelectedSlot))
			{
				OnPropertyChanged(nameof(IsRotovapBottleSelected));
				OnPropertyChanged(nameof(IsCentrifugeBottleSelected));
				OnPropertyChanged(nameof(IsSampleBottleSelected));
				OnPropertyChanged(nameof(IsRotovapEmptySelected));
				OnPropertyChanged(nameof(IsRotovapNotEmptySelected));
				OnPropertyChanged(nameof(IsCentrifugeToRotovapSelected));
				OnPropertyChanged(nameof(IsCentrifugeCondensateCollectionSelected));
				OnPropertyChanged(nameof(IsCentrifugeResidueCollectionSelected));
				OnPropertyChanged(nameof(IsCentrifugeWashLiquidSelected));
				OnPropertyChanged(nameof(IsSampleCondensateSelected));
				OnPropertyChanged(nameof(IsSampleResidueSelected));
				OnPropertyChanged(nameof(SelectedRotovapBottle));
				OnPropertyChanged(nameof(SelectedCentrifugeBottle));
				OnPropertyChanged(nameof(SelectedSampleBottle));
				OnPropertyChanged(nameof(HasExperimentInfo));
			}
		}

		// 添加一个公共的OnPropertyChanged方法，允许外部调用
		public void OnPropertyChanged(string propertyName)
		{
			base.OnPropertyChanged(propertyName);

			if (propertyName == nameof(SelectedSlot))
			{
				OnPropertyChanged(nameof(IsRotovapBottleSelected));
				OnPropertyChanged(nameof(IsCentrifugeBottleSelected));
				OnPropertyChanged(nameof(IsSampleBottleSelected));
				OnPropertyChanged(nameof(IsRotovapEmptySelected));
				OnPropertyChanged(nameof(IsRotovapNotEmptySelected));
				OnPropertyChanged(nameof(IsCentrifugeToRotovapSelected));
				OnPropertyChanged(nameof(IsCentrifugeCondensateCollectionSelected));
				OnPropertyChanged(nameof(IsCentrifugeResidueCollectionSelected));
				OnPropertyChanged(nameof(IsCentrifugeWashLiquidSelected));
				OnPropertyChanged(nameof(IsSampleCondensateSelected));
				OnPropertyChanged(nameof(IsSampleResidueSelected));
				OnPropertyChanged(nameof(SelectedRotovapBottle));
				OnPropertyChanged(nameof(SelectedCentrifugeBottle));
				OnPropertyChanged(nameof(SelectedSampleBottle));
				OnPropertyChanged(nameof(HasExperimentInfo));
			}
		}
	}
}
